//
//  HomePageTableViewController.m
//  news
//
//  Created by lanou on 15/12/16.
//  Copyright © 2015年 lanou. All rights reserved.
//

#import "HomePageTableViewController.h"
#import "ShufflingFigureView.h"
#import "ShufflingFigure.h"
#import "NewsIntroduction.h"
#import "OneImageTableViewCell.h"
#import "ThreeImageTableViewCell.h"
#import "NewsDetailsViewController.h"
#import "MoreimageDetailsViewController.h"
#import "SearchTableViewController.h"

@interface HomePageTableViewController ()<UIScrollViewDelegate, UISearchResultsUpdating, UISearchBarDelegate>

@property (nonatomic, retain) ShufflingFigureView *shufflingFigureView;

@property (nonatomic, retain) NSArray *headerArray;

@property (nonatomic, retain) NSMutableArray *shufflingFigureArray;

@property (nonatomic, retain) NSMutableArray *newsIntroductionArray;

@property (nonatomic, strong) UIView *xialaView;

@property (nonatomic, retain) NSMutableDictionary *typeDic;

@property (nonatomic, strong) UIScrollView *headerScrollView;

@property (nonatomic, strong) UIView *headerView;

@property (nonatomic, retain) NSTimer *buttonTimer;

@property (nonatomic, retain) NSString *tid;

@property (nonatomic, retain) NSString *numberNews;

@property (nonatomic, strong) UISearchController *searchC;

@property (nonatomic, strong) HomePageTableViewController *homePageTVC;

@end

@implementation HomePageTableViewController

#pragma mark -
#pragma mark ---懒加载---

- (NSArray *)headerArray
{
    if (!_headerArray) {
        _headerArray = @[@"头条", @"娱乐", @"军事", @"时尚", @"科技", @"财经", @"家居", @"历史", @"社会", @"影视", @"教育", @"情感", @"艺术", @"政务", @"健康"];
    }
    return _headerArray;
}

- (NSMutableDictionary *)typeDic
{
    if (!_typeDic) {
        _typeDic = [[NSMutableDictionary alloc] init];
    }
    return _typeDic;
}

#pragma mark -
#pragma mark ---网络解析---

- (void)josnShufflingFigure:(NSString *)string
{
    LoadingAnimationView *loadingView = [[LoadingAnimationView alloc] init];
    [loadingView beginLoadingWithView:self.view];
    
    NSString *url = [NSString stringWithFormat:@"http://c.m.163.com/nc/article/list/%@/0-%@.html",string, self.numberNews];
    [LORequestManger GET:url success:^(id response) {
        
        NSDictionary *dic = (NSDictionary *)response;
        
        self.shufflingFigureArray = [[NSMutableArray alloc] init];
        
        for (NSDictionary *ads in dic[string][0][@"ads"]) {
            if ([ads[@"tag"] isEqualToString:@"doc"]) {
                
            } else {
                ShufflingFigure *shufflingFigure = [[ShufflingFigure alloc] init];
                [shufflingFigure setValuesForKeysWithDictionary:ads];
                [self.shufflingFigureArray addObject:shufflingFigure];
            }
        }
        
        self.newsIntroductionArray = [[NSMutableArray alloc] init];
        
        for (NSDictionary *news in dic[string]) {
            if ([news[@"skipType"] isEqualToString:@"live"] || [news[@"subtitle"] isEqualToString:@"原创"]) {
                
            } else {
            NewsIntroduction *newsIntroduction = [[NewsIntroduction alloc] init];
            [newsIntroduction setValuesForKeysWithDictionary:news];
            [self.newsIntroductionArray addObject:newsIntroduction];
            }
        }
        
        [self.tableView reloadData];
        
        [loadingView endLoading];
        
        [self.tableView footerEndRefreshing];
        
        [self.tableView headerEndRefreshing];
        
        self.navigationController.navigationBar.translucent = NO;
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (void)josnType
{
    NSString *url = @"http://c.m.163.com/nc/topicset/ios/subscribe/manage/listspecial.html";
    [LORequestManger GET:url success:^(id response) {
        
        NSDictionary *dic = (NSDictionary *)response;
        
        for (NSDictionary *tList in dic[@"tList"]) {
            [self.typeDic setObject:tList[@"tid"] forKey:tList[@"tname"]];
        }
        
        
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"%@",error);
    }];
}

- (NSString *)tid
{
    if (!_tid) {
        _tid = @"T1348647853363";
    }
    return _tid;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"新网";
    
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    
    self.numberNews = @"20";
    
    [self josnShufflingFigure:self.tid];
    
    
    [self josnType];
    
    __weak HomePageTableViewController *homePageTVC = self;
    
    //上拉
    [self.tableView addHeaderWithCallback:^{
        
        [homePageTVC josnShufflingFigure:homePageTVC.tid];
        
//        [homePageTVC.tableView headerEndRefreshing];
    }];
    
    
    //下拉
    [self.tableView addFooterWithCallback:^{
        static int number = 1;
        
        number++;
        
        homePageTVC.numberNews = [NSString stringWithFormat:@"%d",20 * number];
        [homePageTVC josnShufflingFigure:homePageTVC.tid];
//        [homePageTVC.tableView footerEndRefreshing];
    }];
    
    [self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"cell"];
    
    [self.tableView registerClass:[OneImageTableViewCell class] forCellReuseIdentifier:@"oneImage"];
    
    [self.tableView registerClass:[ThreeImageTableViewCell class] forCellReuseIdentifier:@"threeImage"];
    
    UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:(UIBarButtonSystemItemSearch) target:self action:@selector(searchAction)];
    
    self.navigationItem.rightBarButtonItem = right;
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
}

#pragma mark -
#pragma mark ---搜索框---
- (void)searchAction
{
    self.searchC = [[UISearchController alloc] initWithSearchResultsController:[[UITableViewController alloc] initWithStyle:(UITableViewStylePlain)]];
    self.searchC.searchResultsUpdater = self;
    self.searchC.searchBar.delegate = self;
    self.searchC.searchBar.placeholder = @"请输入搜索内容";
    self.searchC.searchBar.prompt = @"搜索";
    self.searchC.dimsBackgroundDuringPresentation = NO;
    self.searchC.hidesNavigationBarDuringPresentation = NO;
    [self.searchC .searchBar sizeToFit];
    
    [self presentViewController:self.searchC animated:YES completion:nil];
}

- (void)updateSearchResultsForSearchController:(UISearchController *)searchController
{
    
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [searchBar resignFirstResponder];
    
    
    SearchTableViewController *searchVC = [[SearchTableViewController alloc] initWithStyle:(UITableViewStylePlain)];
    
    UINavigationController *navC = [[UINavigationController alloc] initWithRootViewController:searchVC];
    searchVC.searchBarText = searchBar.text;
    
    searchVC.title = [NSString stringWithFormat:@"%@的搜索结果",searchBar.text];
    
    [self.searchC dismissViewControllerAnimated:YES completion:nil];
    [self presentViewController:navC animated:YES completion:nil];
    
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Incomplete implementation, return the number of sections
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete implementation, return the number of rows
    return self.newsIntroductionArray.count;
}


- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    NewsIntroduction *newsIntroduction = self.newsIntroductionArray[indexPath.row];
    
    // Configure the cell...
    
    if (indexPath.row == 0 && self.shufflingFigureArray.count) {
        
#pragma mark ---轮播图---
        
        //轮播图
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell" forIndexPath:indexPath];
        
        NSArray *cellArray = cell.contentView.subviews;
        for (UIView *view in cellArray) {
            [view removeFromSuperview];
        }

        
        _shufflingFigureView = [[ShufflingFigureView alloc] initWithFrame:cell.bounds target:self action:@selector(topImageViewAction) shufflingFigureArray:self.shufflingFigureArray];
        [cell.contentView addSubview:_shufflingFigureView];
        
        UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(10, cell.bounds.size.height - 1, kWidth - 20, 1)];
        lineView.backgroundColor = [UIColor grayColor];
        [cell.contentView addSubview:lineView];
        
        return cell;
        
    } else if (newsIntroduction.digest.length) {
        OneImageTableViewCell *oneImageCell = [tableView dequeueReusableCellWithIdentifier:@"oneImage" forIndexPath:indexPath];
        
        oneImageCell.newsIntroduction = newsIntroduction;
        
        return oneImageCell;
    } else {
        ThreeImageTableViewCell *threeImageCell = [tableView dequeueReusableCellWithIdentifier:@"threeImage"];
        
        threeImageCell.newsIntroduction = newsIntroduction;
        
        return threeImageCell;
        
    }
    
}

#pragma mark -
#pragma mark ---进入新闻详情页面---

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.searchC) {
        [self.searchC dismissViewControllerAnimated:YES completion:nil];
    }
    if (indexPath.row || !self.shufflingFigureArray.count) {
        
        NewsIntroduction *newsIntroduction = self.newsIntroductionArray[indexPath.row];
        
        if (newsIntroduction.digest.length) {
            NewsDetailsViewController *newsDetailsC = [[NewsDetailsViewController alloc] init];
            newsDetailsC.docid = newsIntroduction.docid;
            newsDetailsC.url_3w = newsIntroduction.url_3w;
            UINavigationController *newsDetailsNavC = [[UINavigationController alloc] initWithRootViewController:newsDetailsC];
            [self presentViewController:newsDetailsNavC animated:YES completion:nil];
        } else {
            
            MoreimageDetailsViewController *moreImageDetailsVC = [[MoreimageDetailsViewController alloc] init];
            moreImageDetailsVC.photosetID = newsIntroduction.photosetID;
            moreImageDetailsVC.titleText = newsIntroduction.title;
            UINavigationController *moreImageDetailsNavc = [[UINavigationController alloc] initWithRootViewController:moreImageDetailsVC];
            [self presentViewController:moreImageDetailsNavc animated:YES completion:nil];
            
            
        }
    }
}


#pragma mark -
#pragma mark ---轮播图点击事件---

- (void)topImageViewAction
{
    NSInteger index = self.shufflingFigureView.contentOffset.x / kWidth;
    if (index == 0) {
        index = self.shufflingFigureView.contentSize.width / kWidth - 1;
    }
    index -= 1;
    ShufflingFigure *shuffingFigure = self.shufflingFigureArray[index];
    
    MoreimageDetailsViewController *moreImageDetailsVC = [[MoreimageDetailsViewController alloc] init];
    moreImageDetailsVC.photosetID = shuffingFigure.url;
    UINavigationController *moreImageDetailsNavc = [[UINavigationController alloc] initWithRootViewController:moreImageDetailsVC];
    [self presentViewController:moreImageDetailsNavc animated:YES completion:nil];
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if (scrollView.contentOffset.x < 0) {
        scrollView.contentOffset = CGPointMake(scrollView.contentSize.width - kWidth, 0);
    }
    if (scrollView.contentOffset.x > scrollView.contentSize.width - kWidth) {
        scrollView.contentOffset = CGPointMake(0, 0);
    }
    
}

//表格高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NewsIntroduction *newsIntroduction = self.newsIntroductionArray[indexPath.row];
    if (indexPath.row == 0 && self.shufflingFigureArray.count) {
        return kWidth / 2 + 10;
    } else if (newsIntroduction.digest.length) {
        return kWidth / 5 + 20;
    } else {
        return kWidth / 4 + 50;
    }
}

//表头高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

#pragma mark -
#pragma mark ---初始化表头视图---

- (UIScrollView *)headerScrollView
{
    if (!_headerScrollView) {
        _headerScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(20, 0, kWidth - 70, 30)];
        _headerScrollView.contentSize = CGSizeMake(kWidth / 6 * self.headerArray.count, self.headerScrollView.bounds.size.height);
        _headerScrollView.showsHorizontalScrollIndicator = NO;
        for (int i = 0; i < self.headerArray.count; i ++) {
            
            UIButton *typeButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
            typeButton.frame = CGRectMake(kWidth / 6 * i, 5, kWidth / 6, 20);
            [typeButton setTitle:self.headerArray[i] forState:(UIControlStateNormal)];
            if (!i) {
                [typeButton setTintColor:[UIColor redColor]];
            } else {
            [typeButton setTintColor:[UIColor blackColor]];
            }
            typeButton.tag = 800 + i;
            [typeButton addTarget:self action:@selector(typeAction:) forControlEvents:(UIControlEventTouchUpInside)];
            [_headerScrollView addSubview:typeButton];
            
        }
    }
    return _headerScrollView;
}

//表头视图
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    self.headerView = [[UIView alloc] init];
    
    UIButton *button = [UIButton buttonWithType:(UIButtonTypeSystem)];
    button.frame = CGRectMake(kWidth - 50, 0, 30, 30);
    [button setBackgroundImage:[UIImage imageNamed:@"xiala"] forState:(UIControlStateNormal)];
    [button addTarget:self action:@selector(xiala) forControlEvents:(UIControlEventTouchUpInside)];
    
    button.tag = 8888;
    
    [self.headerView addSubview:button];
    
    self.headerView.backgroundColor = [UIColor whiteColor];
    
    [self.headerView addSubview:self.headerScrollView];
    
    return self.headerView;
}

- (void)typeAction:(id)sender
{
    for (int i = 0; i < self.headerArray.count; i ++) {
        UIButton *typeButton = [(UIButton *)self.headerScrollView viewWithTag:(800 + i)];
        [typeButton setTintColor:[UIColor blackColor]];
    }
    UIButton *button = (UIButton *)sender;
    NSString *str = self.typeDic[self.headerArray[button.tag - 800]];
    [button setTintColor:[UIColor redColor]];
    if (button.tag < 802) {
        
    } else if (button.tag < (self.headerArray.count - 2 + 800)) {
        [self.headerScrollView setContentOffset:CGPointMake(kWidth / 6 * (button.tag - 800 - 2), 0) animated:YES];
    }
    if ([self.tid isEqualToString:str]) {
        
    } else {
        
        self.tid = str;
        
        self.numberNews = @"20";
        
        [self.tableView headerBeginRefreshing];
    }
    
}

#pragma mark -
#pragma mark ---计时器里的数组下标和下拉状态---

static int i = 0;

static BOOL isXiala = NO;

- (void)xialatypeAction:(id)sender
{
    
    
    UIButton *button = (UIButton *)sender;
    
    for (int i = 0; i < self.headerArray.count; i ++) {
        UIButton *typeButton = (UIButton *)[self.headerScrollView viewWithTag:(800 + i)];
        [typeButton setTintColor:[UIColor blackColor]];
    }
    UIButton *button1 = (UIButton *)[self.headerScrollView viewWithTag:800 + button.tag - 1200];
    [button1 setTintColor:[UIColor redColor]];
    if (button.tag < 1202) {
        
    } else if (button.tag < (self.headerArray.count - 2 + 1200)) {
        self.headerScrollView.contentOffset = CGPointMake(kWidth / 6 * (button.tag - 1200 - 2), 0);
    } else {
        self.headerScrollView.contentOffset = CGPointMake(kWidth / 6 * (button.tag - 1200), 0);
    }
    
    
    NSString *str = self.typeDic[self.headerArray[button.tag - 1200]];
    
    
    if (self.buttonTimer) {
        i = 0;
        [self.buttonTimer invalidate];
    }
    
    isXiala = NO;
    
    NSArray *viewArray = self.xialaView.subviews;
    for (UIView *view in viewArray) {
        [view removeFromSuperview];
    }
    
    UIButton *xialaButton2 = (UIButton *)[self.headerView viewWithTag:8888];
    
    [UIView animateWithDuration:0.5 animations:^{
        
        self.xialaView.frame = CGRectMake(0, 64, kWidth, 0);
        xialaButton2.transform = CGAffineTransformRotate(xialaButton2.transform, M_PI);
    } completion:^(BOOL finished) {
        [self.xialaView removeFromSuperview];
    }];
    
    
    if ([self.tid isEqualToString:str]) {
        
    } else {
        self.tid = str;
        
        self.numberNews = @"20";
        
        [self.tableView headerBeginRefreshing];
        
    }
}


#pragma mark -
#pragma mark ---下拉列表---

- (void)xiala
{
    UIButton *xialaButton2 = (UIButton *)[self.headerView viewWithTag:8888];
    if (self.buttonTimer) {
        i = 0;
        [self.buttonTimer invalidate];
    }
    if (isXiala) {
        isXiala = NO;
        
        for (int i = 0; i < self.headerArray.count; i ++) {
            UIButton *button = (UIButton *)[self.xialaView viewWithTag:(1200 + i)];
            [button removeFromSuperview];
        }
        
        UIButton *xialaButton = (UIButton *)[self.xialaView viewWithTag:1111];
        
        
        [UIView animateWithDuration:0.5 animations:^{
            
            xialaButton.transform = CGAffineTransformRotate(xialaButton.transform, M_PI);
            xialaButton2.transform = CGAffineTransformRotate(xialaButton2.transform, M_PI);
            
            self.xialaView.frame = CGRectMake(0, 64, kWidth, 0);
            
        } completion:^(BOOL finished) {
            
            [self.xialaView removeFromSuperview];
            
        }];
        
        
    } else {
        isXiala = YES;
        
        
        self.xialaView = [[UIView alloc] initWithFrame:CGRectMake(0, 64, kWidth, 30)];
        self.xialaView.backgroundColor = [UIColor colorWithRed:226/255.0 green:62/255.0 blue:67/255.0 alpha:0.98];
        
        [self.tableView.superview addSubview:self.xialaView];
        
        UIButton *button = [UIButton buttonWithType:(UIButtonTypeSystem)];
        button.frame = CGRectMake(kWidth - 50, 0, 30, 30);
        [button setBackgroundImage:[UIImage imageNamed:@"xiala"] forState:(UIControlStateNormal)];
        
        button.tag = 1111;
        
        [button addTarget:self action:@selector(xiala) forControlEvents:(UIControlEventTouchUpInside)];
        [self.xialaView addSubview:button];
        
        
        [UIView animateWithDuration:0.5 animations:^{
            
            button.transform = CGAffineTransformRotate(button.transform, M_PI);
            
            xialaButton2.transform = CGAffineTransformRotate(xialaButton2.transform, M_PI);
            
            self.xialaView.frame = CGRectMake(0, 64, kWidth, 200);
            
        } completion:^(BOOL finished) {
            
            self.buttonTimer = [NSTimer scheduledTimerWithTimeInterval:0.01 target:self selector:@selector(jiazaiButton) userInfo:nil repeats:YES];
            
        }];
    }
    
}



- (void)jiazaiButton
{
    
    UIButton *typeButton = [UIButton buttonWithType:(UIButtonTypeSystem)];
    [typeButton setTitle:self.headerArray[i] forState:(UIControlStateNormal)];
    
    int a = i;
    if (a > 4) {
        a -= ((a / 5) * 5);
    }
    int b = i / 5;
    typeButton.frame = CGRectMake(kWidth / 12 + kWidth / 6 * a, 40 + 30 * b, kWidth / 6, 20);
    [typeButton setTintColor:[UIColor blackColor]];
    typeButton.tag = 1200 + i;
    [typeButton addTarget:self action:@selector(xialatypeAction:) forControlEvents:(UIControlEventTouchUpInside)];
    
    [self.xialaView addSubview:typeButton];
    i++;
    if (i == self.headerArray.count) {
        i = 0;
        [self.buttonTimer invalidate];
    }
}


/*
 // Override to support conditional editing of the table view.
 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the specified item to be editable.
 return YES;
 }
 */

/*
 // Override to support editing the table view.
 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
 if (editingStyle == UITableViewCellEditingStyleDelete) {
 // Delete the row from the data source
 [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
 } else if (editingStyle == UITableViewCellEditingStyleInsert) {
 // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
 }
 }
 */

/*
 // Override to support rearranging the table view.
 - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
 }
 */

/*
 // Override to support conditional rearranging of the table view.
 - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
 // Return NO if you do not want the item to be re-orderable.
 return YES;
 }
 */

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
